import { FileHistory, STORAGE_KEYS } from '../types';

/**
 * 读取本地文件
 */
export function readFile(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = (event) => {
      const result = event.target?.result;
      if (typeof result === 'string') {
        resolve(result);
      } else {
        reject(new Error('文件读取失败'));
      }
    };
    
    reader.onerror = () => {
      reject(new Error('文件读取错误'));
    };
    
    reader.readAsText(file, 'UTF-8');
  });
}

/**
 * 下载文件到本地
 */
export function downloadFile(content: string, filename: string = 'config.yaml'): void {
  const blob = new Blob([content], { type: 'text/yaml;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  link.style.display = 'none';
  
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  
  URL.revokeObjectURL(url);
}

/**
 * 生成唯一ID
 */
export function generateId(): string {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

/**
 * 格式化时间
 */
export function formatTime(date: Date): string {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).format(date);
}

/**
 * 保存文件历史记录
 */
export function saveFileHistory(filename: string, content: string): void {
  try {
    const history = getFileHistory();
    const newRecord: FileHistory = {
      id: generateId(),
      filename,
      content,
      timestamp: new Date(),
      size: new Blob([content]).size
    };
    
    // 限制历史记录数量为50条
    const updatedHistory = [newRecord, ...history].slice(0, 50);
    
    localStorage.setItem(STORAGE_KEYS.FILE_HISTORY, JSON.stringify(updatedHistory));
  } catch (error) {
    console.error('保存文件历史失败:', error);
  }
}

/**
 * 获取文件历史记录
 */
export function getFileHistory(): FileHistory[] {
  try {
    const historyStr = localStorage.getItem(STORAGE_KEYS.FILE_HISTORY);
    if (!historyStr) return [];
    
    const history = JSON.parse(historyStr);
    // 转换时间戳为Date对象
    return history.map((item: any) => ({
      ...item,
      timestamp: new Date(item.timestamp)
    }));
  } catch (error) {
    console.error('获取文件历史失败:', error);
    return [];
  }
}

/**
 * 删除文件历史记录
 */
export function deleteFileHistory(id: string): void {
  try {
    const history = getFileHistory();
    const updatedHistory = history.filter(item => item.id !== id);
    localStorage.setItem(STORAGE_KEYS.FILE_HISTORY, JSON.stringify(updatedHistory));
  } catch (error) {
    console.error('删除文件历史失败:', error);
  }
}

/**
 * 清空文件历史记录
 */
export function clearFileHistory(): void {
  try {
    localStorage.removeItem(STORAGE_KEYS.FILE_HISTORY);
  } catch (error) {
    console.error('清空文件历史失败:', error);
  }
}

/**
 * 检查文件扩展名
 */
export function isYAMLFile(filename: string): boolean {
  const ext = filename.toLowerCase().split('.').pop();
  return ext === 'yaml' || ext === 'yml';
}

/**
 * 获取文件名（不含扩展名）
 */
export function getFileNameWithoutExt(filename: string): string {
  return filename.replace(/\.[^/.]+$/, '');
}

/**
 * 确保文件名有正确的扩展名
 */
export function ensureYAMLExtension(filename: string): string {
  if (!isYAMLFile(filename)) {
    return filename + '.yaml';
  }
  return filename;
}